<template>
    <div>
        <el-form :inline="true" :model="condition" class="search-form" label-width="120px">
            <el-row>
                <el-col :span="8">
                    <el-form-item label="作业港口">
                        <select-port v-model="condition['search_EQ_portCode']"></select-port>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="船名">
                        <el-input v-model="condition['search_LIKE_shipName']"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="航次">
                        <el-input v-model="condition['search_LIKE_voyage']"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <!--<el-col :span="8">-->
                    <!--<el-form-item label="箱号">-->
                        <!--<el-input v-model="condition['search_LIKE_containerId']"></el-input>-->
                    <!--</el-form-item>-->
                <!--</el-col>-->
                <el-col :span="8">
                    <el-form-item label="结算月度起">
                        <el-date-picker v-model="condition['search_GTE_accountMonth']"
                                        :picker-options="startPickerOptions" value-format="yyyy-MM" type="month"
                                        placeholder="起始日期"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="结算月度止">
                        <el-date-picker v-model="condition['search_LTE_accountMonth']"
                                        :picker-options="endPickerOptions" value-format="yyyy-MM" type="month"
                                        placeholder="结束日期"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="结算单位">
                        <search-custom @selectName="v=>condition['search_LIKE_accountUnit']=v" :isShipAgent="true"></search-custom>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-button type="primary" class="ml-120" @click="loadData">查 询</el-button>
                    <el-button @click="handleExport">导出Excel</el-button>
                </el-col>
            </el-row>
        </el-form>
        <el-row type="flex" justify="end" class="mt-10 ">
            <el-col :span="16" style="display: flex;justify-content: space-between">
                <title-point color="#449DFF">
                    <div slot="content">总箱数 : <span style="font-size: 16px">{{ totalBox }}</span></div>
                </title-point>
                <title-point color="#50B155">
                    <div slot="content">总箱TEU : <span style="font-size: 16px">{{ totalTeu }}</span></div>
                </title-point>
                <title-point color="#30C8CA">
                    <div slot="content">收费总金额 : <span style="font-size: 16px">{{ totalMoney | filterMoney }} </span>元
                    </div>
                </title-point>
            </el-col>
        </el-row>
        <el-table :data="list" v-loading="listLoading" show-summary :summary-method="getSummary" border stripe
                  max-height="500" class="mt-10">
            <el-table-column type="index" label="序号" fixed="left"  width="55">
                <template slot-scope="scope">
                    <div v-bg="scope.row.portName">{{ scope.row.index }}</div>
                </template>
            </el-table-column>
            <el-table-column prop="portName" label="作业港口"  min-width="120">
                <template slot-scope="scope">
                    <div v-bg="scope.row.portName">{{ scope.row.portName }}</div>
                </template>
            </el-table-column>
            <el-table-column prop="shipName" label="船名"  min-width="120">
                <template slot-scope="scope">
                    <div v-bg="scope.row.portName">{{ scope.row.shipName }}</div>
                </template>
            </el-table-column>
            <el-table-column prop="voyage" label="航次"  min-width="120">
                <template slot-scope="scope">
                    <div v-bg="scope.row.portName">{{ scope.row.voyage }}</div>
                </template>
            </el-table-column>
            <el-table-column prop="total" label="箱数量"  min-width="120">
                <template slot-scope="scope">
                    <div v-bg="scope.row.portName">{{ scope.row.total }}</div>
                </template>
            </el-table-column>
            <el-table-column prop="totalTeu" label="箱TEU"  min-width="120">
                <template slot-scope="scope">
                    <div v-bg="scope.row.portName">{{ scope.row.totalTeu }}</div>
                </template>
            </el-table-column>
            <el-table-column prop="accountFee" label="收费金额"  min-width="120">
                <template slot-scope="scope">
                    <div v-bg="scope.row.portName" :style="scope.row.portName==='小计'&&'font-weight:600'">{{
                        scope.row.accountFee }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="createDateTime" label="结算时间"  min-width="160">
                <template slot-scope="scope">
                    <div v-bg="scope.row.portName">{{ scope.row.createDateTime }}</div>
                </template>
            </el-table-column>
            <el-table-column prop="accountUnit" label="结算单位"  min-width="120">
                <template slot-scope="scope">
                    <div v-bg="scope.row.portName">{{ scope.row.accountUnit }}</div>
                </template>
            </el-table-column>
            <el-table-column prop="createBy" label="结算人"  min-width="120">
                <template slot-scope="scope">
                    <div v-bg="scope.row.portName">{{ scope.row.createBy }}</div>
                </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注"  min-width="120">
                <template slot-scope="scope">
                    <div v-bg="scope.row.portName">{{ scope.row.remark }}</div>
                </template>
            </el-table-column>
            <el-table-column fixed="right" align="center" label="操作"  width="140">
                <template slot-scope="scope">
                    <div v-bg="scope.row.portName">
                        <el-button v-if="scope.row.portName!=='小计'&&power('TALLY_BILL_CASHLIST:DETAIL')" size="small"
                                   type="text"
                                   @click="handleSee(scope.row)">查看
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-row class="bottom mt-10" type="flex" justify="space-between" v-show="total>0">
            <div class="oper">

            </div>
            <el-pagination class="page" @size-change="size=>pageInfo.iDisplayLength=size"
                           layout="total, sizes, prev, pager, next, jumper"
                           :current-page.sync="pageInfo.pageStart" :page-sizes="pageInfo.pageArr"
                           :page-size="pageInfo.iDisplayLength" :total="total">
            </el-pagination>
        </el-row>
        <cash-form ref="cashForm"></cash-form>
    </div>
</template>

<script>
    import { getBalanceCash } from "@/api/balance/balance";
    import searchCustom from '@/components/autocomplete/autoSearchCustom'
    import cashForm from './cashForm'
    import titlePoint from '../common/title-point'
    import selectPort from '@/components/select/selectPort'
    import { newExportExcel } from "@/utils/newExport";

    export default {
        name: "现结查询",
        components: {
            searchCustom, cashForm, titlePoint, selectPort
        },
        data() {
            return {
                condition: {
                    search_EQ_portCode: '',
                    search_LIKE_shipName: '',
                    search_LIKE_voyage: '',
                    search_GTE_accountMonth: '',
                    search_LTE_accountMonth: '',
                    search_LIKE_accountUnit: '',
                },
                list: [],
                dialogForm: false,
                total: 0,
                pageInfo: this.$defalutPage(),
                listLoading: false,
                totalBox: 0,
                totalTeu: 0,
                totalMoney: 0,
                created: true,
            }
        },
        mounted() {
            let day = sessionStorage.getItem('cashIndexFirst')
            let lastDay = sessionStorage.getItem('cashIndexLast')
            this.condition['search_GTE_accountMonth'] = day.substr(0, 7)
            this.condition['search_LTE_accountMonth'] = lastDay.substr(0, 7)
            this.loadData()
        },
        activated() {
            if (!this.created) {
                this.loadData()
            }
        },
        directives: {
            bg: {
                inserted(el, binding) {
                    if (binding.value === '小计') {
                        el.parentNode.parentNode.style.backgroundColor = '#dddddd'
                    }
                },
                update(el, binding) {
                    if (binding.value === '小计') {
                        el.parentNode.parentNode.style.backgroundColor = '#dddddd'
                    }
                },
            }
        },
        methods: {
            loadData() {
                this.listLoading = true
                let params = this.$assist.copySearchConditions(this.condition)
                params.iDisplayStart = this.pageInfo.pageStart - 1
                params.iDisplayLength = this.pageInfo.iDisplayLength
                params.sortType = '-createDateTime'
                getBalanceCash(params).then(res => {
                    this.created = false
                    let data = res.data
                    let name = []
                    let newData = []
                    this.totalBox = 0
                    this.totalTeu = 0
                    this.totalMoney = 0
                    for (let i = 0; i < data.aaData.length; i++) {
                        const el = data.aaData[i]
                        this.totalBox = this.totalBox + Number(el.total)
                        console.log(this.totalBox)
                        this.totalTeu = this.totalTeu + Number(el.totalTeu)
                        this.totalMoney = this.totalMoney + Number(el.accountFee)
                        let nameLength = 0
                        if (name.includes(el.accountUser)) {
                            newData.push({ ...el, index: i + 1 })
                            if (i === data.aaData.length - 1) {
                                let accountFee = 0
                                for (let j = 0; j < newData.length; j++) {
                                    const nd = newData[j]
                                    if (nd.accountUser === el.accountUser) {
                                        accountFee = accountFee + Number(nd.accountFee)
                                    }
                                }
                                newData.push({
                                    portName: '小计',
                                    accountFee: parseFloat(accountFee).toFixed(2),
                                    accountUser: el.accountUser
                                })
                            }
                        } else {
                            if (name.length > nameLength) {
                                let accountFee = 0
                                for (let j = 0; j < newData.length; j++) {
                                    const nd = newData[j]
                                    if (nd.accountUser === data.aaData[i - 1].accountUser) {
                                        accountFee = accountFee + Number(nd.accountFee)
                                    }
                                }
                                newData.push({
                                    portName: '小计',
                                    accountFee: parseFloat(accountFee).toFixed(2),
                                    accountUser: data.aaData[i - 1].accountUser
                                })
                            }
                            name.push(el.accountUser)
                            nameLength = nameLength + 1
                            newData.push({ ...el, index: i + 1 })
                        }
                    }
                    console.log(newData)
                    console.log(name)
                    this.total = data.iTotalRecords
                    this.listLoading = false
                    this.list = newData
                    // this.list = data.aaData

                })
            },
            handleSee(item) {
                this.$refs.cashForm.dialogForm = true
                this.$refs.cashForm.loadData(item.id)
            },
            handleChangeEnd(val) {
                let setVal = val;
                if (val) {
                    setVal = val.split(" ")[0] + " 23:59:59";
                }
                this.condition["search_LTE_accountMonth"] = setVal;
            },
            getSummary(params) {
                const { columns, data } = params
                const sums = [];
                columns.forEach((column, index) => {
                    if (index === 1) {
                        sums[index] = '合计';
                        return;
                    }
                    const values = data.map(item => parseFloat(item[column.property]));
                    if (!values.every(value => isNaN(value)) && column.property === 'accountFee') {
                        sums[index] = parseFloat(this.totalMoney).toFixed(2)
                        sums[index] += ' ';
                    } else {
                        sums[index] = '';
                    }
                });
                return sums;
            },
            handleExport() {
                let map = new Map();
                map.set("portName", "作业港口")
                map.set("shipName", "船名")
                map.set("voyage", "航次")
                map.set("total", "箱数量")
                map.set("totalTeu", "箱TEU")
                map.set("accountFee", "收费金额")
                map.set("accountTime", "结算时间")
                map.set("accountUnit", "结算单位")
                map.set("accountUser", "结算人")
                map.set("remark", "备注")

                let params = this.$assist.copySearchConditions(this.condition)
                params.iDisplayStart = this.pageInfo.pageStart - 1
                params.iDisplayLength = 9999
                params.sortType = '-createDateTime'
                params.search_EQ_planType = 'CX'
                getBalanceCash(params).then(res => {
                    let exportRecords = [];
                    let exportArr = res.data.aaData;
                    exportArr.forEach(record => {
                        let exportRecord = {};
                        for (let [key, value] of map.entries()) {
                            exportRecord[value] = record[key];
                        }
                        exportRecords.push(exportRecord);
                    });
                    newExportExcel("现结查询", exportRecords);
                })
            }

        },
        computed: {
            startPickerOptions() {
                let endDate = this.condition["search_LTE_accountMonth"];
                return {
                    disabledDate(time) {
                        if (endDate) {
                            return time.getTime() > new Date(endDate).getTime();
                        } else {
                            return false;
                        }
                    }
                };
            },
            endPickerOptions() {
                let startDate = this.condition["search_GTE_accountMonth"];
                return {
                    disabledDate(time) {
                        if (startDate) {
                            return time.getTime() < new Date(startDate).getTime();
                        } else {
                            return false;
                        }
                    }
                };
            },
        },
        watch: {
            pageInfo: {
                deep: true,
                handler: function () {
                    this.loadData()
                }
            }
        },
        filters: {
            filterMoney(val) {
                return val ? parseFloat(val).toFixed(2) : ''
            }
        }
    }
</script>

<style scoped>

</style>
